package com.mes.schedule.dao;

import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.stereotype.Repository;

import com.mes.common.dao.BasicDao;
import com.mes.common.exception.db.BaseDBException;
import com.mes.common.util.Page;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

import com.mes.schedule.dao.iface.IScheduleEventDao;
import com.mes.schedule.domain.ScheduleEvent;

@Repository
public class ScheduleEventDao extends BasicDao<ScheduleEvent> implements IScheduleEventDao{
	private static final Log log = LogFactory.getLog(ScheduleEventDao.class);
	
	/**
	 * @author lcs
	 * @see the method use for ScheduleStateFind
	 * @param scheduleUid
	 * @param fromDate
	 * @param toDate
	 * @param page
	 * @return
	 * @throws BaseDBException
	 */
	public List<ScheduleEvent> getUnHandleEvents(String scheduleUid, Date fromDate, Date toDate, Page page)
			throws BaseDBException {
		List list = null;
		try {
			Session session = this.getSession();
			StringBuilder hql = new StringBuilder();
			hql.append(" from " + ScheduleEvent.class.getName() + " where ");
			hql.append("   scheduleUid like ? || '%' ");
			hql.append(" and eventState=" + ScheduleEvent.EVENTSTATE_DRAFT);
			hql.append(" and createTime between ? and ? ");
			hql.append("  order by eventType,createTime");
			Query query = session.createQuery(hql.toString());

			query.setString(0, scheduleUid);
			query.setTimestamp(1, fromDate);
			query.setTimestamp(2, toDate);
			if (page != null)
				page.pagePro(query);
			list = query.list();
			// by lm
			// 为了调度方案最后保存时再存盘,暂时让其先脱离hibernate持久态
			// for(Object object:list)
			// {
			// session.evict(object);
			// }
		} catch (DataAccessResourceFailureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	/**
	 * @author lcs
	 * @see the method use for ScheduelStatefind
	 * @param scheduleUid
	 * @param fromDate
	 * @param toDate
	 * @param eventState
	 * @param eventType
	 * @param page
	 * @return
	 * @throws BaseDBException
	 */
	public List<ScheduleEvent> getAllEvents(String scheduleUid, Date fromDate, Date toDate, Integer eventState,
			String eventType, Page page) throws BaseDBException {
		List<ScheduleEvent> ScheduleEventList = null;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, -3);
		Date startDate = calendar.getTime();

		try {
			Session session = this.getSession();
			Criteria crit = session.createCriteria(ScheduleEvent.class);

			crit.add(Restrictions.eq("scheduleUid", scheduleUid));
			if (fromDate != null && !("".equals(fromDate))) {
				crit.add(Restrictions.gt("createTime", fromDate));
			}

			if (toDate != null && !("".equals(toDate))) {
				crit.add(Restrictions.lt("createTime", toDate));
			}
			if (eventState != null && !("".equals(eventState))) {
				crit.add(Restrictions.eq("eventState", eventState));
			}
			if (eventType != null && !("".equals(eventType))) {
				crit.add(Restrictions.eq("eventType", eventType));
			}

			crit.addOrder(Property.forName("createTime").desc());
			crit.addOrder(Property.forName("eventState").asc());
			// 如果需要进行分页处理，则调用如下语句
			if (page != null)
				page.pagePro(crit);
			ScheduleEventList = crit.list();
		} catch (DataAccessResourceFailureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ScheduleEventList;

	}
	
	/**
	 * @see the method use for ScheduleEventManager
	 * @param scheduleUid
	 * @param eventType
	 * @param sourceUid
	 * @return
	 * @throws BaseDBException
	 */
	public ScheduleEvent getUnHandleEvent(String scheduleUid, String eventType, String sourceUid)
			throws BaseDBException {
		ScheduleEvent scheduleEvent = null;
		try {

			Session session = this.getSession();
			Criteria crit = session.createCriteria(ScheduleEvent.class);
			crit.add(Restrictions.eq("scheduleUid", scheduleUid));
			crit.add(Restrictions.eq("eventState", ScheduleEvent.EVENTSTATE_DRAFT));
			crit.add(Restrictions.eq("eventType", eventType));
			crit.add(Restrictions.eq("sourceUid", sourceUid));
			crit.addOrder(Order.desc("createTime"));
			crit.setMaxResults(1);

			scheduleEvent = (ScheduleEvent) crit.uniqueResult();
		} catch (DataAccessResourceFailureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return scheduleEvent;
	}

	/**
	 * @see the method use for ScheduleEventManager
	 * @param scheduleEvent
	 * @return
	 * @throws BaseDBException
	 */
	public ScheduleEvent getUnHandleEvent(ScheduleEvent scheduleEvent) throws BaseDBException {
		// TODO Auto-generated method stub
		return this.getUnHandleEvent(scheduleEvent.getScheduleUid(), scheduleEvent.getEventType(),
				scheduleEvent.getSourceUid());
	}
	
	/**
	 * see the method use for ScheduleSyncManager
	 * @param eventType
	 * @return
	 * @throws BaseDBException
	 */
	public List<ScheduleEvent> getUnHandleEvents(String eventType) throws BaseDBException {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * see the method use for ScheduleSyncManager
	 * @param scheduleUid
	 * @param eventType
	 * @return
	 * @throws BaseDBException
	 */
	public List<ScheduleEvent> getUnHandleEvents(String scheduleUid, String eventType) throws BaseDBException {
		List list = null;
		try {
			Session session = this.getSession();
			StringBuilder hql = new StringBuilder();
			hql.append(" from " + ScheduleEvent.class.getName() + " where ");
			// lqm todo
			// 暂时用like来解决 车间级调度问题
			// 以后应该有更明确的指定
			hql.append("   scheduleUid like ? || '%' ");
			hql.append(" and eventState=" + ScheduleEvent.EVENTSTATE_DRAFT);
			if (eventType != null)
				hql.append(" and eventType=? ");
			hql.append("  order by createTime");
			Query query = session.createQuery(hql.toString());

			query.setString(0, scheduleUid);
			if (eventType != null)
				query.setString(1, eventType);
			list = query.list();
			// by lm
			// 为了最后保存时再存盘,暂时先脱离持久态
			// for(Object object:list)
			// {
			// session.evict(object);
			// }
		} catch (DataAccessResourceFailureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * see the method use for ScheduleSyncManager
	 * @param scheduleUid
	 * @param eventType
	 * @param fromDate
	 * @param toDate
	 * @param page
	 * @return
	 * @throws BaseDBException
	 */
	public List<ScheduleEvent> getUnHandleEvents(String scheduleUid, String eventType, Date fromDate, Date toDate,
			Page page) throws BaseDBException {
		List list = null;
		try {
			Session session = this.getSession();
			StringBuilder hql = new StringBuilder();
			hql.append(" from " + ScheduleEvent.class.getName() + " where ");
			hql.append("   scheduleUid=? ");
			hql.append(" and eventState=" + ScheduleEvent.EVENTSTATE_DRAFT);
			hql.append(" and eventType=? ");
			hql.append(" and createTime between ? and ? ");
			hql.append("  order by createTime");
			Query query = session.createQuery(hql.toString());

			query.setString(0, scheduleUid);
			query.setString(1, eventType);
			query.setTimestamp(2, fromDate);
			query.setTimestamp(3, toDate);
			if (page != null)
				page.pagePro(query);
			list = query.list();
			// by lm
			// 为了调度方案最后保存时再存盘,暂时让其先脱离hibernate持久态
			// for(Object object:list)
			// {
			// session.evict(object);
			// }
		} catch (DataAccessResourceFailureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}


	
}
